<template>
  <j-form-container :disabled="formDisabled">
    <a-form-model  ref="ruleForm" :rules="rules" :model="form" slot="detail">
      <!-- 政策库显示扩展属性 -->
      <a-row >
            <a-col v-for="(item, key) in classAttrList" :key="key" :span="handleCol(item)" >
      
      <a-form-model-item  
        class="attr-item"
       
        :label="item.name"
        v-bind="handleLayout(item)"
        :prop="item.name"
      >
        <a-date-picker
          v-if="item.name == '政策发布时间'"
          v-model="form[item.name]"
          valueFormat="YYYY-MM-DD"
        />
        <!-- :disabled="!!hteFile && !!hteFile.id" -->
        <a-select
           
          v-if="item.name == '业务板块'"
          v-model="form[item.name]"
          @change="handleBusiness"
           show-search
          :filter-option="filterOption"
        >
          
          <a-select-option v-for="d in businessList" :key="d.name">{{ d.name }}</a-select-option>
        </a-select>
        <!-- <a-select
          show-search
          v-if="item.name == '责任机构'"
          v-model="form[item.name]"
          :filter-option="false"
          :not-found-content="fetching ? undefined : null"
          @search="fetchMechanism"
          @change="(value,option) => handleSelectSearchChange(value,option)"
        >
          <a-spin v-if="fetching" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in selectSearchData" :key="d.value">{{ d.text }}</a-select-option>
        </a-select> -->

         <a-select

          v-if="item.name == '责任机构'"
          v-model="form[item.name]"
          show-search
          :filter-option="filterOption"

          @change="(value,option) => handleSelectSearchChange(value,option)"
        >
          
          <a-select-option v-for="d in selectSearchData" :key="d.name">{{ d.name }}</a-select-option>
        </a-select>
        <a-cascader
          v-if="item.name == '适用地区'"
          :placeholder="'请输入'+item.name"
         :field-names="{ label: 'label', value: 'label',children:'children' }"
          :options="cityData"
          change-on-select
          v-model="form[item.name]"
          @change="onChangeArea"
        />
        <a-select v-if="item.name == '政策级别'" v-model="form[item.name]"  show-search
          :filter-option="filterOption">
          <a-select-option v-for="d in policylLevel" :key="d.name">{{ d.name }}</a-select-option>
        </a-select>
        <a-select v-if="item.name == '所属专题'"  v-model="form[item.name]"  show-search
          :filter-option="filterOption">
         <a-select-option v-for="d in specialList" :key="d.name">{{ d.name }}</a-select-option>
        </a-select>
        <a-radio-group
          v-model="form[item.name]"
          v-if="item.name == '是否长期性政策'"
          @change="onEffctChange"
        >
          <a-radio :value="d.name" v-for="d in dics.flagDics" :key="d.name" :defaultChecked="d.defaultChecked">{{ d.name }}</a-radio>
        </a-radio-group>
        <a-date-picker
          v-model="form[item.name]"
          v-if="item.name == '有效时间至' "
          :disabled="!!form['是否长期性政策'] && form['是否长期性政策'] == '否'"
          valueFormat="YYYY-MM-DD"
          @change=" onRangeTimeChange"
        />
         <a-radio-group
          v-model="form[item.name]"
          v-if="item.name == '是否有员工数量要求'"
        >
          <a-radio :value="d.name" v-for="d in dics.flagDics" :key="d.name" :defaultChecked="d.defaultChecked">{{ d.name }}</a-radio>
        </a-radio-group>
        <a-cascader
         
          v-model="form[item.name]"
          :placeholder="'请输入'+item.name"
           :options="cityData"
           change-on-select
           :field-names="{ label: 'label', value: 'label',children:'children' }"
          v-if="item.name == '企业注册地'"
          
        ></a-cascader>

        <a-textarea v-model="form[item.name]" v-if="item.name == '经营范围'" :auto-size="true" placeholder="如无明确说明则填“不限”" :maxLength="4000" />

        <a-date-picker
          v-if="item.name == '申报开始时间'"
          valueFormat="YYYY-MM-DD"
          v-model="form[item.name]"
          @change="onDeclareChange"
          :disabled-date="disabledStartDate"
        />
        <a-date-picker
          v-if="item.name == '申报结束时间'"
          valueFormat="YYYY-MM-DD"
          v-model="form[item.name]"
         :disabled-date="disabledEndDate"
          @change="onDeclareChange"
        />

        <a-input v-if="item.name == '申报状态'" :disabled="true" v-model="form[item.name]" />
        <a-input v-if="item.name == '文件状态'" :disabled="true" v-model="form[item.name]" />
        <a-input-number
          :min="0"
         
          :formatter="value => `${value}月`"
          :parser="value => value.replace('月', '')"
          :disabled="!!form['是否长期性政策'] && form['是否长期性政策'] == '否'"
          v-if="item.name == '申报周期'"
          v-model="form[item.name]"
        />

        <a-select
        v-if="item.name == '适用行业（可多选）'"
        v-model="form[item.name]"
        mode = "multiple"
        show-search
        :filter-option="filterOption"
      >
        <a-select-option v-for="d in industryList" :key="d.name">{{ d.name }}</a-select-option>
      </a-select>
     
        <a-select
          v-if="item.name == '要求企业资质（可多选）'"
          v-model="form[item.name]"
          mode = "multiple"
          show-search
          :filter-option="filterOption"
        >

          <a-select-option v-for="d in qualificationList" :key="d.name">{{ d.name }}</a-select-option>
        </a-select>

        <a-input-number
          :min="0"
          :formatter="value => `${value}年`"
          :parser="value => value.replace('年', '')"
          v-if="item.name == '企业成立时间（下限）'"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '注册资金（下限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '企业总人数（下限）'"
          :precision="0"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '企业总人数（上限）'"
          :precision="0"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '研发人员数（下限）'"
          :precision="0"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :max="100"
          :formatter="value => `${value}%`"
          :parser="value => value.replace('%', '')"
          v-if="item.name == '研发人员占比（下限）'"
          placeholder="%"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '博士学位人数（下限）'"
          placeholder="人"
          :precision="0"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '硕士学位人数（下限）'"
          placeholder="人"
          :precision="0"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '本科学历人数（下限）'"
          placeholder="人"
          :precision="0"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          :formatter="value => `${value}人`"
          :parser="value => value.replace('人', '')"
          v-if="item.name == '大专及以上人数（下限）'"
          placeholder="人"
          :precision="0"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度资产总额（下限）'"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度资产总额（上限）'"
          placeholder="单位万元"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度营业收入（下限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度营业收入（上限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度主营业务收入（下限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度主营业务收入（上限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          
          v-if="item.name == '上年度纳税额（下限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度纳税额（上限）'"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度研发费用（下限）'"
          v-model="form[item.name]"
        />
        <a-input-number
          :min="0"
          placeholder="单位万元"
          :formatter="value => `${value}万元`"
          :parser="value => value.replace('万元', '')"
          v-if="item.name == '上年度研发费用（上限）'"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          v-if="item.name == '国家标准（下限）'"
          :formatter="value => `${value}项`"
          :parser="value => value.replace('项', '')"
          placeholder="项"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          v-if="item.name == '行业标准（下限）'"
          placeholder="项"
          :formatter="value => `${value}项`"
          :parser="value => value.replace('项', '')"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          v-if="item.name == '团体标准（下限）'"
          placeholder="项"
          :formatter="value => `${value}项`"
          :parser="value => value.replace('项', '')"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          v-if="item.name == '国内发明专利（下限）'"
          placeholder="项"
          :formatter="value => `${value}项`"
          :parser="value => value.replace('项', '')"
          v-model="form[item.name]"
        />

        <a-input-number
          :min="0"
          v-if="item.name == '国内实用新型（下限）'"
          placeholder="项"
          :formatter="value => `${value}项`"
          :parser="value => value.replace('项', '')"
          v-model="form[item.name]"
        />

        <a-textarea
         
          v-if="item.name == '其他要求'"
          v-model="form[item.name]"
          :auto-size="true"
          :maxLength="4000" 
        />

        <a-textarea v-if="item.name == '扶持力度'" v-model="form[item.name]" :auto-size="true" :maxLength="4000" />
        <a-textarea v-if="item.name == '申报要求'" v-model="form[item.name]" :auto-size="true" :maxLength="4000" />
        <a-input v-if="item.name == '扶持金额'" v-model="form[item.name]" />
        <a-textarea v-if="item.name == '相关企业'" v-model="form[item.name]" :auto-size="true" :maxLength="4000"/>
        <a-textarea v-if="item.name == '相关部门'" v-model="form[item.name]" :auto-size="true" :maxLength="4000"/>
         <a-textarea v-if="item.name == '适用对象'" v-model="form[item.name]" :auto-size="true" :maxLength="4000"/>
         <a-textarea v-if="item.name == '扶持内容'" v-model="form[item.name]" :auto-size="true" :maxLength="4000"/>
      </a-form-model-item>
              </a-col >
      </a-row>
    </a-form-model>
  </j-form-container>
</template>

<script>
import { getAction } from '@/api/manage'
import { formatDate } from '@/utils/util'
import debounce from 'lodash/debounce'
import { policylLevel,flagDics } from '@/views/library/dics'

export default {
  name: 'LibFileAttr',
  components: {},
  props: {
    formDisabled: {
      type: Boolean,
      default: false
    },
    parentId: {
      type: String,
      default: null
    },
    classAttrList: {
      type: Array,
      default: () => {}
    },
    formItemLayout:{
      type:Object,
      default:() => {}
    },
    hteFile:{
      type:Object,
      default:() => {},
      required:false

    }
  },
  data() {
    this.fetchMechanism = debounce(this.fetchMechanism, 800)
    return {
      cityData :[],
      selectSearchData: [],
      fetching: false,
      dics: {
        policylLevel,
        flagDics
      },
      labelColRow: {
        xs: { span: 21 },
        sm: { span: 3 }
      },
      urls: {
        getTreeList: '/lib/hteFileClass/getTreeList',
        listAttr: '/lib/hteLibFile/attrs',
        specialList: "/policy/policySpecial/list",
        mechanismList: "/policy/policyMechanism/list",
        businessList: "/policy/policyBusiness/list",
        areaInfo:'/manage/codeInfo/areaInfo',
        codeInfo:'/manage/codeInfo/list'
      },
      //   form: this.$form.createForm(this, { name: 'form' }),
      effectTimeShow: false,
      form: {},
      rules: {},
      specialList:[],
      businessList:[],
      policylLevel:[],
      industryList:[],
      qualificationList:[],
      businessPrefix:''
    }
  },
  watch: {
    classAttrList: {
      handler: function(value, oldValue) {
        
        this.initForm(value)
      },
      deep: true
    }
  },
  mounted () {
     this.initForm(this.classAttrList)
  },
  created() {},
  methods: {
    handleCol(item){
      let name = item.name;
        if(name == '扶持力度' || name == '经营范围' ||  name == '申报要求' || name == '相关企业' || name == '相关部门' || name == '其它要求'){
          return 24
        }else{
          return 12
        }
    },
    handleLayout(item){
        let name = item.name;
        if(name == '扶持力度' || name == '经营范围' ||  name == '申报要求' || name == '相关企业' || name == '相关部门' || name == '其它要求'){
         return {labelCol: {
              xs: { span: 24 },
              md: { span: 4 },
            },

            wrapperCol: {
              xs: { span: 24 },
              md: { span: 18 },
            }}
        }else{
          return {labelCol: {
              xs: { span: 18 },
              sm: { span: 8 },
            },

            wrapperCol: {
              xs: { span: 20 },
              sm: { span: 12 },
            }}
        }
    },
    formWatch(value) {},
    declareStatus() {
      var that = this
      var name = '申报状态'
      var startTime = this.form['申报开始时间']
      var endTime = this.form['申报结束时间']
      var nowTiem = new Date(formatDate(new Date().getTime(), 'yyyy-MM-dd')).getTime()
      if (!!startTime && !!endTime) {
        
        if (new Date(startTime).getTime() > nowTiem) {
          this.$set(that.form, name, '未开始')
        } else if (new Date(endTime).getTime() < nowTiem) {
          this.$set(that.form, name, '已截止')
        } else {
          var day = new Date(endTime).getTime() - nowTiem
          day = day / (24 * 60 * 60 * 1000)
          this.$set(that.form, name, `还剩${day}天`)
        }
      }
    },
    initForm(value) {
      
      let that = this
      this.businessPrefix = ''
      let fromData = {}
      this.$refs.ruleForm.clearValidate()
      this.classAttrList.forEach(item => {

        that.$set(that.form, item.name, item.content)
        let rules = [{ required: true, message: '请输入' + item.name,trigger: 'change' }]

        if (item.required) {
          that.$set(that.rules,item.name+'',rules)
        }

        if ((item.name == '适用地区' || item.name == '企业注册地') && !!item.content) {
          var content = item.content.split('/')
          that.$set(that.form, item.name, content)
        }
        if(item.name == '适用地区'){
          if(!!item.content){
              that.getMechanismList({area:item.content })
          }else{
                that.getMechanismList()
          }
           
        }
        if((item.name == '要求企业资质（可多选）' || item.name == '适用行业（可多选）')){
          if(!item.content){
            that.$set(that.form, item.name, undefined)
          }else{
            that.$set(that.form, item.name, item.content.split(','))
          }
        }


        //  if (item.name == '是否长期性政策'  && !item.content) {
         
        //   that.$set(that.form, item.name, '否')
        // }
       
      })
     let areaFlag =  this.classAttrList.find(item=>{
         return item.name == '适用地区'
      })
      if(!areaFlag){
        that.getMechanismList({})
      }
      that.form = Object.assign({}, that.form)
      // this.declareStatus()
      this.initDics()
      
    },
    initDics(){
      getAction(this.urls.specialList, {pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
          this.specialList= res.result.records
        }
      })
      getAction(this.urls.businessList, {  pageNo: 1, pageSize: -1 ,column:"code",order:"Asc"}).then(res => {
        if (res.success) {
          this.businessList= res.result.records
        }
      })
      this.selectSearchData = []
      
      getAction(this.urls.areaInfo, {  pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
          this.cityData= res.result
        }
      })
      getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'政策库政策级别' }).then(res => {
        if (res.success) {
          this.policylLevel= res.result.records
        }
      })
      getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'行业类型' }).then(res => {
        if (res.success) {
          this.industryList= res.result.records
        }
      })

      //  getAction('/libraryCompany/hteLibCompanySize/industryNameList',{}).then(res=>{
         
      //       this.industryList = res.result.records
      //   });
      getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'企业资质' }).then(res => {
        if (res.success) {
          this.qualificationList= res.result.records
        }
      })

     
    },
    handleBusiness(value,option){
      let business =this.businessList.find(item=>{
        return item.name === value
      })
      this.businessPrefix = business&&business.code;
       
    },
     getMechanismList(data = {area:'默认不加载数据！'}){
       
       getAction(this.urls.mechanismList, Object.assign({  pageNo: 1, pageSize: -1 },data) ).then(res => {
        if (res.success) {
            this.selectSearchData = res.result.records
            // this.$forceUpdate()
        }
      })
    },
    attrSetValueByName(value, name) {
      let that = this
      this.classAttrList.forEach((item, index) => {
        if (item.name == name) {
          item.content = value
          that.$set(that.classAttrList, index, item)
        }
      })
    },
    fetchMechanism(value) {
      let that = this
      this.fetching = true
      value = !!value?value:'-1';
      getAction(this.urls.mechanismList, { keyword: value, pageNo: 1, pageSize: 100 }).then(res => {
        if (res.success) {
          const data = res.result.records.map(user => ({
            text: `${user.name}`,
            value: user.name
          }))
          that.selectSearchData = data

          that.fetching = false
        }
      })
    },
    handleSelectSearchChange(value, option) {
      
      // Object.assign(this, {
      //   selectSearchData: [],
      //   fetching: false
      // })
     
    },
    onChange(e) {
      
    },
    onChangeArea(value){
      this.$set(this.form,'责任机构', '')
      this.getMechanismList({area:value.join("/")})
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    onDeclareChange(e) {
      // this.declareStatus()
    },
     disabledStartDate(startValue) {
       
     
      const endValue = this.form['申报结束时间']
      if (!startValue || !endValue) {
        return false;
      }
      return new Date(startValue)  >= new Date(endValue) ;
    },
    disabledEndDate(endValue) {
      
      const startValue = this.form['申报开始时间'];
      if (!endValue || !startValue) {
        return false;
      }
      return  new Date(startValue)  >= new Date(endValue) ;
    },
    onRangeTimeChange(date, dateString) {
      
      console.log(date, dateString)
    },
    onEffctChange(e) {
      
      if (e.target.value == '是') {
        this.effectTimeShow = false
      } else {
        this.$set(this.form, '有效时间至', '')
        this.$set(this.form, '申报周期', '')
        this.effectTimeShow = true
      }
    },

    checkClassAttr() {
      let flag = false
      this.$refs.ruleForm.validate((err, values) => {
        if (err) {
          flag = true
        }
      })
      return flag
    },
    getClassAttr() {
      // this.$refs.ruleForm.validate((err, values) => {
      //   if (err) {
    
          this.classAttrList.forEach(attr => {
            attr.content = this.form[attr.name]
         
            if (
              (attr.name == '适用地区' || attr.name == '企业注册地' ) &&
              !!this.form[attr.name] 
            ) {
              var rangTimeStr = this.form[attr.name].join('/')
              attr.content = rangTimeStr
            }
             if (
              ( attr.name == '要求企业资质（可多选）' || attr.name == '适用行业（可多选）') &&
              !!this.form[attr.name] 
            ) {
              var rangTimeStr = this.form[attr.name].join(',')
              attr.content = rangTimeStr
            }
          })
      //   }
      // })
      return this.classAttrList
    }
  }
}
</script>
<style >
.attr-item .ant-form-item-label label{
    word-break: break-all;
    white-space: normal;

}
.attr-item textarea{
  line-height: 1.8
}
</style>
<style scoped>
.app-container {
  margin-top: 5px;
}
.attr-box {
  width: 100%;
  /* display: flex;
  align-content: flex-start;
  flex-flow: row wrap; */
}

.attr-item {
  /* width: 50%;
  margin-right: 0;
  margin-bottom: 20px; */
  
}

.attrTitle {
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #000;
}
.ant-form-item {
  margin-bottom: 5px !important;
}
.ant-input-number {
  width: 100%;
}
</style>